#include <iostream>
#include <cstdio>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include "Comm.hpp"

#define CREATOR "creator"
#define USER "user"


const int gdefaultid = -1;
const int gsize = 4096;
const int projid = 0x66;
const int gmode = 0666;
const std::string pathname = ".";

class Shm
{
    void CreateHelper(int flag)
    {
        printf("key: 0x%x\n", _key);
        _shmid = shmget(_key, _size, flag);
        if (_shmid < 0)
        {
            ERR_EXIT("shmget error");
        }

        printf("shmid: %d\n", _shmid);
    }

    void Create()
    {
        CreateHelper(IPC_CREAT | IPC_EXCL | gmode);
    }

    void Attach()
    {
        _start_mem = shmat(_shmid, nullptr, 0);
        if ((long long)_start_mem < 0)
        {
            ERR_EXIT("shmat error");
        }

        printf("attach success\n");
    }

    void Get()
    {
        CreateHelper(IPC_CREAT);
    }

    void Destroy()
    {
        if (_shmid == gdefaultid)
        {
            return;
        }

        int n = shmctl(_shmid, IPC_RMID, 0);
        if (n > 0)
        {
            printf("shmctl delete shmid: %d success\n", _shmid);
        }
        else
        {
            ERR_EXIT("shmctl error");
        }
    }

public:
    Shm(const std::string &pathname, int projid, const std::string &identity)
        : _shmid(gdefaultid), _size(gsize), _start_mem(nullptr), _identity(identity)
    {
        umask(0);
        _key = ftok(pathname.c_str(), projid);
        if (_key < 0)
        {
            ERR_EXIT("ftok error");
        }

        if (_identity == CREATOR)
        {
            Create();
        }
        else if (_identity == USER)
        {
            Get();
        }

        Attach();
    }

    void *VirutualAddr()
    {
        printf("virtual addr: %p\n", _start_mem);
        return _start_mem;
    }

    int Size()
    {
        return _size;
    }

    ~Shm()
    {
        if(_identity == CREATOR)
        {
            Destroy();
        }
    }

private:
    int _shmid;
    int _size;
    key_t _key;
    void *_start_mem;
    std::string _identity;
};
